package com.zhao.fishingguideserver.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.ObjectMetadata;
import com.zhao.fishingguideserver.config.OssConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * 阿里云OSS服务类
 */
@Service
@Slf4j
public class OssService {
    
    @Autowired(required = false)
    private OSS ossClient;
    
    @Autowired
    private OssConfig ossConfig;
    
    /**
     * 上传文件到OSS
     * @param file 文件
     * @param folder 文件夹路径（如：fish-images/）
     * @return 文件访问URL
     */
    public String uploadFile(MultipartFile file, String folder) {
        try {
            // 验证文件
            if (file == null || file.isEmpty()) {
                throw new IllegalArgumentException("文件不能为空");
            }
            
            // 生成文件名
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null || originalFilename.trim().isEmpty()) {
                throw new IllegalArgumentException("文件名无效");
            }
            
            // 验证文件扩展名
            int lastDotIndex = originalFilename.lastIndexOf(".");
            if (lastDotIndex == -1 || lastDotIndex == originalFilename.length() - 1) {
                throw new IllegalArgumentException("文件必须有扩展名");
            }
            
            String extension = originalFilename.substring(lastDotIndex);
            String fileName = folder + UUID.randomUUID().toString() + extension;
            
            // 设置文件元数据
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentLength(file.getSize());
            metadata.setContentType(file.getContentType());
            
            // 上传文件
            InputStream inputStream = file.getInputStream();
            ossClient.putObject(ossConfig.getBucketName(), fileName, inputStream, metadata);
            
            // 返回文件访问URL
            String fileUrl = ossConfig.getDomain() + "/" + fileName;
            log.info("文件上传成功: {}", fileUrl);
            return fileUrl;
            
        } catch (IOException e) {
            log.error("文件上传失败", e);
            throw new RuntimeException("文件上传失败: " + e.getMessage());
        }
    }
    
    /**
     * 上传文件到OSS（使用指定文件名）
     * @param file 文件
     * @param folder 文件夹路径
     * @param fileName 指定文件名（不包含扩展名）
     * @return 文件访问URL
     */
    public String uploadFileWithName(MultipartFile file, String folder, String fileName) {
        try {
            // 验证文件
            if (file == null || file.isEmpty()) {
                throw new IllegalArgumentException("文件不能为空");
            }
            
            // 获取文件扩展名
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null || originalFilename.trim().isEmpty()) {
                throw new IllegalArgumentException("文件名无效");
            }
            
            int lastDotIndex = originalFilename.lastIndexOf(".");
            if (lastDotIndex == -1 || lastDotIndex == originalFilename.length() - 1) {
                throw new IllegalArgumentException("文件必须有扩展名");
            }
            
            String extension = originalFilename.substring(lastDotIndex);
            String fullFileName = folder + fileName + extension;
            
            // 设置文件元数据
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentLength(file.getSize());
            metadata.setContentType(file.getContentType());
            
            // 上传文件
            InputStream inputStream = file.getInputStream();
            ossClient.putObject(ossConfig.getBucketName(), fullFileName, inputStream, metadata);
            
            // 返回文件访问URL
            String fileUrl = ossConfig.getDomain() + "/" + fullFileName;
            log.info("文件上传成功: {}", fileUrl);
            return fileUrl;
            
        } catch (IOException e) {
            log.error("文件上传失败", e);
            throw new RuntimeException("文件上传失败: " + e.getMessage());
        }
    }
    
    /**
     * 删除OSS文件
     * @param fileUrl 文件URL
     */
    public void deleteFile(String fileUrl) {
        try {
            // 从URL中提取文件名
            String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
            ossClient.deleteObject(ossConfig.getBucketName(), fileName);
            log.info("文件删除成功: {}", fileName);
        } catch (Exception e) {
            log.error("文件删除失败", e);
            throw new RuntimeException("文件删除失败: " + e.getMessage());
        }
    }
}
